/**
 * Created by Anard on 2017/4/17.
 */
let mysql = require('mysql');
let log = require('../util/log.js');
let variable = require('../data/variable.js');

let client = module.exports;
let connection;
let NND = {};
//连接数据库
NND.init = function () {
    connection = mysql.createConnection(variable.mysql);
    connection.connect();
    log.p('数据库连接成功');
    connection.on('error', function (err) {
        log.e('db error:', err.code);
        // 如果是连接断开，自动重新连接
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            NND.init();
        } else if (err.code === 'ECONNREFUSED') {
            NND.init();
        } else {
            throw err;
        }
    });
};

//查询
NND.query = function (sql, args, cb) {
    console.log(sql);
    connection.query(sql, args, function (err, rows, fields) {
        cb(err, rows);
    });
};

/**
 * init database
 */
client.init = function () {
    if (!!connection) {
        return client;
    } else {
        NND.init();
        client.insert = NND.query;
        client.update = NND.query;
        client.delete = NND.query;
        client.query = NND.query;
        return client;
    }
};

client.end = function () {
    connection.end();
};

client.init();

//关闭连接
//connection.end();